import axios from 'axios'
import router from '@/router'
import { ElMessage } from 'element-plus'
// import base from '@/utils/config/base'
import { getToken, removeToken } from '@/utils/auth'

// axios.defaults.baseURL = base.prod
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

// 请求拦截器
axios.interceptors.request.use(function (request) {
  // let method = request.method === 'get' ? 'params' : 'data'
  // request[method] = { ...request[method], t: new Date().getTime() }

  request.headers.token = getToken() || ''
  return request
})

// 响应拦截器
axios.interceptors.response.use(function (response) {
  if (response.data.code == 0) {
    return response.data
  } else if (response.config.responseType === 'blob') {
    return response
  } else if (response.data.code === undefined) {
    return response
  } else if (response.data.code === 401) {
    ElMessage({
      type: 'warning',
      message: '请重新登录'
    })
    removeToken()
    // location.reload()
    router.push('/login')
  } else {
    return response.data
  }

  ElMessage.closeAll()
  ElMessage.error(response.data.msg)
  return Promise.reject(response.data)
}, (error) => {
  // const { response, message } = error
  // if (response.status == 500) {
  //   ElMessage.closeAll()
  // } else {
  //   if (!document.querySelector('.el-message--error')) {
  //     ElMessage.closeAll()
  //     ElMessage.error({ message: '网络连接失败，请联系管理员', duration: 3000, showClose: true })
  //   }
  // }
  ElMessage.closeAll()
  ElMessage.error({ message: '网络连接失败，请联系管理员', duration: 3000, showClose: true })
  return Promise.reject(error)
})
